﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using EzDesk.Core.Model;
using System.Collections.Specialized;
using System.Security.Policy;
using System.Net;
using System.IO;
using System.Web;
using EzDesk.Core.CoreImpl.Repositories;
using EzDesk.Core.CoreImpl.Repositories.Interface;
using EzDesk.Core.CoreImpl.Services;

namespace EzDesk.Core.CoreImpl.Services.AppPortal
{
    public class AppPortalService : IAppPortalService
    {
        #region [ 构造器 ]
        private IAppSessionService _appSessionService;
        private IAppRepository _appRepository;

        public AppPortalService(IAppSessionService appSessionService, IAppRepository appRepository)
        {
            this._appSessionService = appSessionService;
            this._appRepository = appRepository;
        }

        // todo: 使用DI重构
        public AppPortalService()
            : this(new AppSessionService(), new AppRepository())
        {
        }
        #endregion

        public HttpContent GetPortalRequests(string httpMethod, string targetUrl, string appName, Guid currentUserId, IList<KeyValuePair<string, string>> formParameters = null)
        {
            CallbackContentBuilder builder = CallbackContentBuilder.CreateBuilder(httpMethod, _appSessionService);

            // 生成NameValueCollection的Form数据
            NameValueCollection formCollection = null;
            if (formParameters != null)
            {
                formCollection = new NameValueCollection();
                foreach (var item in formParameters)
                {
                    formCollection.Add(item.Key, item.Value);
                }
            }

            HttpContent requestContent = builder.GetReqest(appName, targetUrl, currentUserId, formCollection);
            return requestContent;
        }


        public string GetAppDomainName(string appName, string userAgent)
        {
            App app = this.GetAppByName(appName);
            try
            {
                return app.Domains.Where(p => p.UserAgentStr == userAgent).Single().Domain;
            }
            catch (Exception ex)
            {
                throw new Exception("找不到对应的Domain", ex);
            };
        }


        public App GetAppByName(string appName)
        {
            return _appRepository.GetAppByName(appName);
        }

        public Guid GetUserIdByToken(string tokenString)
        {
            return ClientTokenPool.Instance.GetUserIdByToken(tokenString);
        }





    }
}